package gupao.concurrency.threads;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LuckCode {
    //这俩语句任一一个加 volatile 就可以避免main执行出现 x = 0 && y = 0的情况
    private static int x = 0, y = 0;
    private static int a = 0, b = 0;

    public static void main(String[] args) throws InterruptedException {
        long i = 0;
        while (true) {
            i++;
            x = 0; y = 0; a = 0; b = 0;
            //开两个线程，第一个线程执行a=1;x=b;第二个线程执行b=1;y=a
            Thread t1 = new Thread(() -> {
                //线程1会比线程2先执行，因此用nanoTime让线程1等待线程2 0.01毫秒
                Utils.waitNanos(10000);
                a = 1;
                x = b;
            });
            Thread t2 = new Thread(() -> {
                b = 1;
                y = a;
            });
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            //等两个线程都执行完毕后拼接结果
            String result = "第" + i + "次执行 x = " + x + ", y = " + y;
            //如果x=0且y=0，则跳出循环
            if (x == 0 && y == 0) {
                System.out.println(result);
                System.out.println("重排序导致结束..");
                break;
            } else {
                System.out.println(result);
            }
        }
    }
}
